package com.haoxuer.discover.quartz.web;

import com.haoxuer.discover.quartz.utils.SchedulerUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InitListener implements ServletContextListener {
  
  private Logger logger = LoggerFactory.getLogger("ada");
  
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    
    Scheduler scheduler = SchedulerUtils.getScheduler();
    if (scheduler == null) {
      return;
    }
    try {
      if (!scheduler.isStarted()) {
        scheduler.start();
        logger.info("初始化定时器成功");
      }
    } catch (SchedulerException e) {
      logger.info("Scheduler启动错误", e);
    }
    
  }
  
  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    Scheduler scheduler = SchedulerUtils.getScheduler();
    if (scheduler == null) {
      return;
    }
    try {
      if (scheduler.isStarted()) {
        scheduler.shutdown();
        logger.info("关闭定时器");
      }
    } catch (SchedulerException e) {
      logger.info("Scheduler关闭错误", e);
    }
  }
}
